from db.db_base import BaseModel
from sqlalchemy import Column, String, Integer, DateTime, Enum, ForeignKey
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func
from apps.location.room.models.room import Room


class Camera(BaseModel):
    __tablename__ = "camera"
    __table_args__ = {'comment': '摄像头表'}
    serial_number = Column(String(100),
                           unique=True,
                           nullable=False,
                           comment="摄像头序列号，厂商所提供的全球唯一标识",
                           )
    model = Column(String(100),
                   comment="摄像头型号",
                   nullable=True,
                   )
    ip_address = Column(String(45),
                        comment="摄像头IP地址",
                        nullable=False,
                        )
    status = Column(Enum('online', 'offline', 'maintenance'),
                    comment="摄像头状态",
                    nullable=False,
                    default='offline')
    last_active = Column(DateTime,
                         nullable=True,
                         comment="最后一次活动时间",
                         server_default=func.now(),
                         onupdate=func.now(),
                         )
    room_id = Column(Integer,
                     ForeignKey('room.id'),
                     nullable=True,
                     comment="房间ID"
                     )
    # 一个房间可以有多个摄像头，每个摄像头只能属于一个房间
    room = relationship("Room", back_populates="cameras")
    # 一个摄像头可以有多个协议
    protocols = relationship(
        "CameraProtocol", back_populates="camera", cascade="all, delete")


class CameraProtocol(BaseModel):
    __tablename__ = 'camera_protocol'
    __table_args__ = {'comment': '摄像头协议表'}
    camera_id = Column(Integer,
                       ForeignKey('camera.id'),
                       nullable=False,
                       comment="摄像头ID")
    protocol = Column(Enum('RTSP', 'WSS', 'HTTP',
                      'HTTPS', 'P2P'),
                      comment="协议类型",
                      nullable=False)
    access_url = Column(String(255),
                        comment="协议的访问地址",
                        nullable=False)
    username = Column(String(100),
                      comment="协议的用户名",
                      )
    password = Column(String(100))
    priority = Column(Integer,
                      default=1,
                      comment="协议的优先级，首先会使用优先级高的协议，1为最高，依次递减",
                      )
    # 每个摄像头可以有多个协议，但每个协议只能属于一个摄像头
    camera = relationship("Camera", back_populates="protocols")
